<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <script src="../../js/load.js"></script>
    <style>
        #fileList {
            width: 100%;
        }

        .dirLevel {
            cursor: pointer;
            text-decoration: underline
        }

        .dirLevel:hover {
            color: blue;
        }
    </style>
</head>

<body>
<div style="width: 100%;height: 100%;">
    <div style="width: 100%;height: 50px;display: flex;flex-direction: row;justify-items: left;align-items: center">
        <label style="padding-left: 20px">Nginx安装目录：</label>
        <input type="text" id="nginxHome" placeholder="请输入安装目录" autocomplete="off" class="layui-input"
               style="width: 300px">
        <button type="button" class="layui-btn" style="padding-left: 20px" onclick="SaveHomeDetail()">保存</button>
        <button type="button" id="editConfig" class="layui-btn layui-btn-danger layui-btn-disabled"
                onclick="EditConfig()">
            编辑配置
        </button>
    </div>
    <div id="fileList">
        <div style="width: 100%;height: 50px;display: flex;flex-direction: row;justify-items: left;align-items: center">
            <i class="layui-icon layui-icon-home" onclick="ChangeNavPrefix(-1)"
               style="margin-right: 10px;margin-left:20px;cursor: pointer;font-size: 25px"></i>
            <span class="layui-breadcrumb" id="prefixNav">

            </span>
            <button style="margin-left: 20px" class="layui-btn layui-btn-sm" onclick="HandleUploadFile()">上传文件</button>
            <button class="layui-btn layui-btn-sm" onclick="HandleUploadDir()">上传压缩包（自动解压）</button>
        </div>
        <div class="layui-fluid">
            <table class="layui-table" lay-data="{id: 'datagrid',height:'full'}" lay-filter="datagrid">
                <thead>
                <tr>
                    <th lay-data="{fixed: 'right', toolbar: '#name'}">名称</th>
                    <th lay-data="{field:'createDate',width:180,align:'center'}">创建时间</th>
                    <th lay-data="{field:'lastModifyDate',width:180,align:'center'}">修改时间</th>
                    <th lay-data="{fixed: 'right', width:170, align:'center', toolbar: '#op2'}">压缩/解压</th>
                    <th lay-data="{fixed: 'right', width:260, align:'center', toolbar: '#op'}">操作</th>
                </tr>
                </thead>
            </table>
            <div style="display: none;">
                <input type="file" name="file" id="file" style="display:none" onchange="HandleRealUpload()"/>
                <input type="file" name="file" id="zip" accept=".zip" style="display:none" onchange="HandleZipRealUpload()"/>
            </div>
        </div>
    </div>
</div>
<script type="text/html" id="name">
    {{#  if(d.checkDir){ }}
    <span class="layui-icon layui-icon-table layui-font-24"></span><span style="margin-left: 10px;" class="dirLevel"
                                                                         onclick="ChangeFilePrefix('{{d.fileName}}')">{{d.fileName}}</span>
    {{#  } else { }}
    <span class="layui-icon layui-icon-file layui-font-24"></span><span style="margin-left: 10px">{{d.fileName}}</span>
    {{#  } }}
</script>
<script type="text/html" id="op2">
    <button class="layui-btn layui-btn-sm" lay-event="HandleZip"><i
            class="layui-icon layui-icon-templeate-1 layui-font-12"></i>压缩
    </button>
    {{#  if(d.fileName.endsWith(".zip")){ }}
    <button class="layui-btn layui-btn-sm layui-btn-primary" lay-event="HandleUnZip"><i
            class="layui-icon layui-icon-export layui-font-12"></i>解压
    </button>
    {{#  } else { }}
    {{#  } }}
 </script>
<script type="text/html" id="op">
    {{#  if(d.checkDir){ }}
    <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="HandleDelete"><i
            class="layui-icon layui-icon-delete layui-font-12"></i>删除
    </button>
    {{#  } else { }}
    <button class="layui-btn layui-btn-sm" lay-event="HandleDownLoad"><i
            class="layui-icon layui-icon-download-circle layui-font-12"></i>下载
    </button>
    <button class="layui-btn layui-btn-sm" lay-event="HandleEdit"><i
            class="layui-icon layui-icon-edit layui-font-12"></i>编辑
    </button>
    <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="HandleDelete"><i
            class="layui-icon layui-icon-delete layui-font-12"></i>删除
    </button>
    {{#  } }}
</script>
</body>
</html>
<script>
    var prefixList = []
    var zipGuid = "";
    var element = layui.element;
    var progressLayer;
    $(function () {
        LoadHomeDetail();
    })

    function LoadHomeDetail() {
        var param = {}
        HttpPost(JSON.stringify(param), 'api/nginx/home/detail', function (result) {
            if (result.code == 0) {
                $("#nginxHome").val(result.data.nginxHome);
                if (result.data.check) {
                    BindTableData();
                    $("#editConfig").removeClass("layui-btn-disabled")
                } else {
                    $("#editConfig").addClass("layui-btn-disabled")
                }
            } else {
                OpenFail(result.msg);
            }
        })
    }

    function SaveHomeDetail() {
        var param = {
            "nginxHome": $("#nginxHome").val()
        }
        HttpPost(JSON.stringify(param), 'api/nginx/home/save', function (result) {
            if (result.code == 0) {
                OpenSuccess("保存成功")
                LoadHomeDetail()
            } else {
                OpenFail(result.msg);
            }
        })
    }

    function EditConfig() {
        OpenDialog('编辑配置文件', 'pages/nginx/nginxconfig_edit.html', 1366, 768)
    }

    //==========================================file===============================================
    function BindTableData() {
        var param = {
            "prefix": GetFilePrefix()
        }
        BindTable("datagrid", "api/nginx/file/list", param, function (result) {

        }, false);
    }

    function GetFilePrefix() {
        var prefix = "";
        for (var i = 0; i < prefixList.length; i++) {
            if (i == prefix.length - 1) {
                prefix += prefixList[i];
            } else {
                prefix += prefixList[i] + "/";
            }
        }
        return prefix;
    }

    function ChangeFilePrefix(fileName) {
        prefixList.push(fileName);
        RenderBread();
        BindTableData();
    }

    function ChangeNavPrefix(index) {
        prefixList = prefixList.slice(0, parseInt(index) + 1);
        RenderBread();
        BindTableData();
    }

    function RenderBread() {
        var html = "";
        for (var i = 0; i < prefixList.length; i++) {
            var prefixString = prefixList[i];
            html += " <a href='#' onclick=ChangeNavPrefix('" + i + "')>" + prefixString + "</a>"
        }
        $("#prefixNav").html(html);
        layui.element.render();
    }

    function HandleUploadFile() {
        $("#file").click();
    }

    function HandleRealUpload() {
        var formData = new FormData();
        var file = document.getElementById("file").files[0];
        formData.append("file", file, file.name);
        formData.append("prefix", encodeURIComponent(GetFilePrefix()))
        var xhr = new XMLHttpRequest();
        progressLayer = layer.open({
           type: 0,
           title: false,
           closeBtn: 0,
           btn: false,
           content: '<div class="layui-progress layui-progress-big" lay-filter="progress" lay-showpercent="true"><div class="layui-progress-bar" lay-percent="0%"></div></div>'
        });
        xhr.upload.addEventListener('progress', function(event) {
           if (event.lengthComputable) {
                var percentage = Math.round((event.loaded * 100) / event.total);
                element.progress('progress',percentage + '%')
           }
        }, false);
        xhr.onreadystatechange = function() {
           if (xhr.readyState === 4) {
              layer.close(progressLayer);
              layer.closeAll();
              if (xhr.status === 200) {
                  OpenSuccessMessage("上传成功")
                  BindTableData();
               }
             }
         };

         xhr.open('POST', GetRootPath()+"api/nginx/file/upload", true);
         xhr.send(formData);
    }

    function HandleUploadDir() {
        $("#zip").click();
    }

    function HandleZipRealUpload() {
        var formData = new FormData();
        var file = document.getElementById("zip").files[0];
        formData.append("file", file, file.name);
        formData.append("prefix", encodeURIComponent(GetFilePrefix()))
        formData.append("autounzip", "1");
        var xhr = new XMLHttpRequest();
        progressLayer = layer.open({
           type: 0,
           title: false,
           closeBtn: 0,
           btn: false,
           content: '<div class="layui-progress layui-progress-big" lay-filter="progress" lay-showpercent="true"><div class="layui-progress-bar" lay-percent="0%"></div></div>'
        });
        xhr.upload.addEventListener('progress', function(event) {
           if (event.lengthComputable) {
                var percentage = Math.round((event.loaded * 100) / event.total);
                element.progress('progress',percentage + '%')
           }
        }, false);
        xhr.onreadystatechange = function() {
           if (xhr.readyState === 4) {
              layer.close(progressLayer);
              layer.closeAll();
              if (xhr.status === 200) {
                  OpenSuccessMessage("上传成功")
                  BindTableData();
               }
             }
         };

         xhr.open('POST', GetRootPath()+"api/nginx/file/upload", true);
         xhr.send(formData);
    }
    
    function HandleZip(RowData) {
        OpenConfirm('确认压缩？', function () {
            zipGuid = getNewGuid();
            var param = {
                "prefix": GetFilePrefix(),
                fileName: RowData.fileName,
                "zipGuid":zipGuid
            }
            HttpPost(JSON.stringify(param), 'api/nginx/file/zip', function (result) {
                if (result.code == 0) {
                    progressLayer = layer.open({
                        type: 0,
                        title: false,
                        closeBtn: 0,
                        btn: false,
                        content: '<div class="layui-progress layui-progress-big" lay-filter="progress" lay-showpercent="true"><div class="layui-progress-bar" lay-percent="0%"></div></div>'
                    });
                    updateProgress(function(){
                        OpenSuccessMessage("压缩成功")
                        BindTableData();
                    })
                } else {
                    OpenFail(result.msg);
                }
            })
        })
    }
    
    function updateProgress(success) {
        var param = {
            "pguid":zipGuid
        }
        HttpPost(JSON.stringify(param), 'api/nginx/file/progress', function (result) {
            if (result.code == 0) {
                if(result.data.obj==100){
                    layer.close(progressLayer);
                    layer.closeAll();
                    success();
                }else{
                    element.progress('progress', result.data.obj + '%')
                    sleep(500);
                    updateProgress(success);
                }
            } else {
                layer.close(progressLayer);
                layer.closeAll();
                OpenFail(result.msg);
            }
        })
    }
    
    function HandleUnZip(RowData) {
        OpenConfirm('确认解压？', function () {
            var param = {
                "prefix": GetFilePrefix(),
                fileName: RowData.fileName
            }
            var loading = layer.load('解压中...', {
                icon: 16,
                shade: 0.01
            })
            HttpPost(JSON.stringify(param), 'api/nginx/file/unzip', function (result) {
                layer.close(loading);
                if (result.code == 0) {
                    OpenSuccessMessage("解压成功")
                    BindTableData();
                } else {
                    OpenFail(result.msg);
                }
            })
        })
    }

    function HandleEdit(RowData) {
        OpenDialog('编辑文件', "pages/nginx/nginxfile_edit.html?prefix=" + encodeURIComponent(GetFilePrefix()) + "&fileName=" + encodeURIComponent(RowData.fileName), 1366, 768)
    }

    function HandleDelete(RowData) {
        OpenConfirm('确认删除？', function () {
            var param = {
                "prefix": GetFilePrefix(),
                fileName: RowData.fileName
            }
            HttpPost(JSON.stringify(param), 'api/nginx/file/delete', function (result) {
                if (result.code == 0) {
                    OpenSuccessMessage("删除成功")
                    BindTableData();
                } else {
                    OpenFail(result.msg);
                }
            })
        })
    }

    function HandleDownLoad(RowData) {
        var url = GetRootPath() + "api/nginx/file/download?prefix=" + encodeURIComponent(GetFilePrefix()) + "&fileName=" + encodeURIComponent(RowData.fileName);
        window.top.open(url);
    }
</script>